package com.webtest.jsptest;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/7/24 9:31
 * <p>
 * HttpServlet:
 * 1. 是一个servlet，继承自GenericServlet，针对于Http协议所定制
 * 2. 在service方法中直接把ServletRequest和ServletResponse转为HttpServletRequest和HttpServletResponse，并调用了重载的service(HttpServletRequest,HttpServletResponse)
 * 在service(HttpServletRequest,HttpServletResponse)中获取了请求方式:request.getMethod()，根据请求方式又创建了doXXX()方法（xxx为具体的请求方式，如doPost,doGet）
 *
 * 3. 实际开发中，直接继承HttpServlet,并根据请求方式覆写doXXX方法即可
 * 4. 好处：直接有针对性的覆盖doXxx（），直接使用HttpServletRequest，不再需要强转。
 *
 * */
public class MyHttpServlet extends GenericServlet {
    private static final long serialVersionUID = -6413458965715974826L;

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            if (servletResponse instanceof HttpServletResponse) {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                service(request, response);
            }
        }
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getMethod();
        if ("GET".equalsIgnoreCase(method)) {
            doGet(request, response);
        }

        if ("POST".equalsIgnoreCase(method)) {
            doPost(request, response);
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // todo
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // todo
    }

}
